package grabbing.ticket.business.service;

import grabbing.ticket.common.util.queue.TicketQueueUtils;
import grabbing.ticket.common.util.redis.RedisTicketUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.CountDownLatch;

@Service
public class TicketService{

    @Autowired
    private TicketQueueUtils queueUtils;
    @Autowired
    private RedisTicketUtils ticketUtils;

    /**
     * 库存初始化
     */
    public void initStore(int num) {
        ticketUtils.cache(num);
    }

    /**
     * 开始消费者
     */
    public void startConsumer() {
        queueUtils.dealTask();
    }

    /**
     * 抢票
     */
    public void getTicket(int userId, int num) {
        queueUtils.addTask(userId,num);
    }

    /**
     * 获取剩余总票数
     */
    public Integer getTotal() {
        return ticketUtils.get();
    }

    /**
     * 抢票测试
     */
    public void testRush(int num) {
        CountDownLatch latch = new CountDownLatch(num);
        for (int i = 0; i < num; i++) {
            new Thread(() -> {
                try {
                    // 阻塞所有线程
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                queueUtils.addTask(1,1);
            }).start();

            latch.countDown();
        }
    }
}
